package com.tjrac.zhaopin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.tjrac.zhaopin.entity.LoginResp;
import com.tjrac.zhaopin.entity.SysUser;
import com.tjrac.zhaopin.service.SysUserService;
import com.tjrac.zhaopin.utils.PasswordUtil;
import com.tjrac.zhaopin.utils.SendMail;
import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@RestController
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/doRegister")
    public R doRegister(@RequestBody SysUser sysUser) {
        return sysUserService.registUser(sysUser);
    }

    @PostMapping("/doLogin")
    public LoginResp doLogin(@RequestBody SysUser sysUser) {
        return sysUserService.login(sysUser);
    }

    @PostMapping("/toSendCodeEmail")
    @Transactional(rollbackFor = Exception.class)
    public R toSendCodeEmail(@RequestParam String toSendCodeEmail) {
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("email", toSendCodeEmail.trim()));
        if (sysUser != null) {
            try {
                String captcha = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
                int sendMail = new SendMail(toSendCodeEmail, captcha).send();
                if (sendMail == 0) {
                    sysUser.setCaptcha(captcha);
                    sysUserService.updateById(sysUser);
                    return R.ok(sysUser.getId());
                } else return R.failed("发送失败！");
            } catch (Exception e) {
                e.printStackTrace();
                return R.failed("发送失败！");
            }
        } else return R.failed("该邮箱未注册！");
    }

    @PostMapping("/resetPasswordByCaptcha")
    @Transactional(rollbackFor = Exception.class)
    public R resetPasswordByCaptcha(@RequestBody ResetPasswordByCaptchaReq req) {
        SysUser sysUser = sysUserService.getById(req.getUserId());
        try {
            if (sysUser.getCaptcha().trim().equals(req.getCaptcha().trim())){
                sysUser.setPassword(new PasswordUtil(req.getPassword().trim()).getEncryptedPwd());
                sysUserService.updateById(sysUser);
                return R.ok("重置成功！");
            }else return R.failed("验证码有误！");
        }catch (Exception e){
            return R.failed("未知错误！");
        }
    }

    @GetMapping("/api/test/testToken")
    public int testToken() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.getPrincipals() != null) {
            SysUser user = (SysUser) subject.getPrincipals().getPrimaryPrincipal();
            user.setToken("");
            sysUserService.updateById(user);
        }
        return 200;
    }

    @GetMapping(value = "/logout")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Void> logout(HttpServletResponse response) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.getPrincipals() != null) {
            SysUser user = (SysUser) subject.getPrincipals().getPrimaryPrincipal();
            user.setToken("");
            sysUserService.updateById(user);
        }
        SecurityUtils.getSubject().logout();
        response.setHeader("x-auth-token", "");
        return ResponseEntity.ok().build();
    }
}

@Data
class ResetPasswordByCaptchaReq{
    private String captcha;
    private String password;
    private int userId;
}
